package com.jtemimal.context;

import cn.gsein.terminal.AbstractTerminal;

import java.util.concurrent.ConcurrentHashMap;

public class TerminalContext {
    // 使用 ThreadLocal 存储每个线程的 ConcurrentHashMap，其中 key 为 host，value 为 Terminal InheritableThreadLocal
    private static final ThreadLocal<ConcurrentHashMap<String, AbstractTerminal>> threadLocalTerminals =
        ThreadLocal.withInitial(ConcurrentHashMap::new);

    // 设置 host 对应的 terminal
    public static void setTerminal(String host, AbstractTerminal terminal) {
        threadLocalTerminals.get().put(host, terminal);
    }

    // 获取 host 对应的 terminal
    public static AbstractTerminal getTerminal(String host) {
        return threadLocalTerminals.get().get(host);
    }

    // 清理当前线程的所有 terminal 映射
    public static void clearTerminals() {
        threadLocalTerminals.get().clear();
    }

    // 移除当前线程的 ThreadLocal 映射（慎用，通常在线程结束时调用）
    public static void removeThreadLocal() {
        threadLocalTerminals.remove();
    }

    // 示例方法：创建并设置 terminal
    public static void createAndSetTerminal(String host, AbstractTerminal terminal) {
//        Terminal terminal = new Terminal(terminalId, host);
        setTerminal(host, terminal);
    }

    // 示例方法：打印当前线程的所有 terminal
    public static void printTerminals() {
        threadLocalTerminals.get().forEach((host, terminal) ->
                System.out.println("Host: " + host + ", Terminal: " + terminal));
    }

    // 示例方法：移除特定 host 的 terminal
    public static void removeTerminal(String host) {
        threadLocalTerminals.get().remove(host);
    }

}